package com.spring.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @author panxingyu
 *
 * 事务管理器工具类
 */
@Component("transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionHolder connectionHolder;

    public void begin() throws SQLException {
        connectionHolder.getConnection().setAutoCommit(false);
    }
    public void commit() throws SQLException {
        connectionHolder.getConnection().commit();
    }
    public void rollback(){
        try {
            connectionHolder.getConnection().rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public void close(){
        try {
            connectionHolder.getConnection().close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 环绕通知
     */
    public Object around(ProceedingJoinPoint joinPoint){
        try {
            begin();
            //执行业务逻辑
            Object o = joinPoint.proceed();
            commit();
            return o;
        }catch (Throwable throwable){
            rollback();
            throw new RuntimeException(throwable);
        }finally {
            close();
        }
    }
}
